var idGame;
var login;
var propositions = new Array();
var robotSelected = null;
var countDownValue;
var winner = null;
var terminateGame = false;
var robots;
var cible;

var XHR = function(method, ad, params) {
	var xhr = new XMLHttpRequest();
	xhr.onload = params.onload || null;
	xhr.open(method, ad);
	if (method == 'POST') {
		xhr.setRequestHeader('Content-Type',
				'application/x-www-form-urlencoded');
	}
	var variables = params.variables || null, str = '';
	for ( var i in variables) {
		str += i + '=' + encodeURIComponent(variables[i]) + '&';
	}
	xhr.send(str);
}

function init() {
	// Connect to the SocketIO server to retrieve ongoing games.
	socket = io.connect();
	socket.on('participants', function(data) {
		var ul = document.getElementById('lesParticipants');
		ul.innerHTML = '';
		for (p in data.participants) {
			var li = document.createElement('li');
			ul.appendChild(li);
			li.appendChild(document.createTextNode(data.participants[p]));
		}
	});
	socket.on('FinalCountDown', function(data) {
		countDownValue = data.FinalCountDown / 1000;
		countDown();
	});
	socket.on('TerminateGame', function(data) {
		terminateGame = true;
		var divProposition = document.getElementById("proposition");
		divProposition.querySelector("h5").innerHTML = "La partie est terminée !";
		if (winner == login) {
			divProposition.setAttribute("class", "panel panel-success");
			document.getElementById("countDown").innerHTML = 
				"Vous avez gagnez la partie !";
		} else {
			divProposition.setAttribute("class", "panel panel-danger");
			document.getElementById("countDown").innerHTML = 
				"Le joueur " + winner + " a gagné la partie.";	
		}
	});
	socket.on('solutions', function(data) {
		console.log("Solutions are :\n" + JSON.stringify(data.solutions));
		getWinner(data.solutions);
		var divProposition = document.getElementById("proposition");
		divProposition.setAttribute("class", "panel panel-warning");
		if (winner == login) {
			divProposition.querySelector("h5").innerHTML = 
				"Vous avez trouvé une solution !";
		} else {
			divProposition.querySelector("h5").innerHTML = 
				"Le joueur " + winner + " a trouvé une solution !";	
		}
	});
	socket.emit('identification', {
		login : document.getElementById('login').value,
		idGame : document.getElementById('idGame').value
	});

	// init game
	idGame = document.getElementById('idGame').value;
	login = document.getElementById('login').value;
	initGame();
}

function initGame() {
	XHR("GET", "/" + idGame, {
		onload : function() {
			var res = JSON.parse(this.responseText);
			// init plateau
			construireTableau(res.board);
			cible = res.target;
			afficherCible();
			robots = res.robots;
			afficherRobots();
			gestionCellule();
		}
	});
}


function moveRobot(idRobot, line, column) {
    propositions.push({
		command : 'move',
		line : line,
		column : column
	});
    
	XHR("POST", "/proposition", {
		onload : function() {
			console.log("Moving robot: " + idRobot + ", " + line + ", " + column);
			console.log(this.responseText);
			
			var res = JSON.parse(this.responseText);
			if (res.state == "INVALID_MOVE") {
				// suppression de la precedente proposition
				propositions.pop();
			} else if (res.state == "SUCCESS") {
				// remplacement de la cible par le robot
				document.getElementById("cell_" + line + "_" + column)
						.removeChild(document.getElementById("cible"));
				// deplacement du robot
				document.getElementById("cell_" + line + "_" + column)
						.appendChild(document.getElementById(idRobot));
			} else if (res.state == "INCOMPLETE") {
				// deplacement du robot
				document.getElementById("cell_" + line + "_" + column)
						.appendChild(document.getElementById(idRobot));
			}
			// desactivation des cellules coloriees
			while (document.querySelector("."+idRobot) != null) {
				document.querySelector("."+idRobot).setAttribute("class", ".cellule");
			}
			selectRobotCell(idRobot);
		},
		variables : {
			idGame : idGame,
			login : login,
			proposition : JSON.stringify(propositions)
		}
	});
}

function selectRobot(idRobot) {
	propositions.push({
		command : 'select',
		robot : idRobot
	});
	
	XHR("POST", "/proposition", {
		onload : function() {
			console.log(this.responseText);
			var res = JSON.parse(this.responseText);
			if (res.state == "INVALID_SELECT") {
				// suppression de la precedente proposition
				propositions.pop();
				alert(res.details);
			} else if (res.state == "INCOMPLETE") {
				var nextPos = res.nextPositions;
				for (var i = 0; i < nextPos.length; i++) {
					var cell = "cell_" + nextPos[i].l + "_"+ nextPos[i].c;
					document.getElementById(cell).setAttribute("class", ""+idRobot);
				}
			}
		},
		variables : {
			idGame : idGame,
			login : login,
			proposition : JSON.stringify(propositions)
		}
	});
}


/*
 * Fonctions plateau
 */

function afficherCible(){
	var cellule_cible = 'cell_' + cible.l + '_' + cible.c;
	var cellule = document.getElementById(cellule_cible);	
	cellule.innerHTML = "<img id='cible' src='../images/cible_" + cible.t
			+ ".png' width='100%' />";
}

function construireTableau(tab) {
	var boardHtml = document.getElementById("board");
	for (var i = 0; i <= 15; i++) {
		var row = boardHtml.insertRow(-1);
		for (var j = 0; j <= 15; j++) {
			var cell = row.insertCell(-1);
			cell.className = "cellule";
			cell.id = "cell_" + i + "_" + j;
			if (tab[i][j].g == 1) {
				cell.style.borderLeft = "10px solid black";
			}
			if (tab[i][j].d == 1) {
				cell.style.borderRight = "10px solid black";
			}
			if (tab[i][j].h == 1) {
				cell.style.borderTop = "10px solid black";
			}
			if (tab[i][j].b == 1) {
				cell.style.borderBottom = "10px solid black";
			}
		}
	}
}

function afficherRobots() {
	for (var i in robots) {
		var robot = robots[i];
		var cellule = document.getElementById('cell_' + robot.line + '_' + robot.column);
		cellule.innerHTML = "<img id='" + robot.color + "' src='../images/robot_" + robot.color
				+ ".png' width='100%' />";
	}
}

function gestionCellule() {
	var cellules = document.querySelectorAll('.cellule');
	var i = 0;
	while (i < cellules.length) {
		var cellule = cellules.item(i);
		// Listener cellules
		addCellListener(cellule);
		i++;
	}
}

function addCellListener(node) {
	node.addEventListener('click', function(e) {
		if (e.currentTarget.querySelector("img") != null) {
			// la cible ou un robot est selectionne
			var imgId = e.currentTarget.querySelector("img").getAttribute('id');
			if (imgId != "cible") {
				// si un robot est selectionne
				if (robotSelected != null) {
					// un robot a pecedemment ete selectionne
					// on desactive les cellules coloriees
					while (document.querySelector("."+robotSelected) != null) {
						document.querySelector("."+robotSelected).setAttribute("class", ".cellule");
					}
				}
				selectRobotCell(imgId);
			} else if (robotSelected != null) {
				// si l'utilisateur deplace le robot sur la cible
				var cell = e.currentTarget.getAttribute("id").split("_");
				moveRobot(robotSelected, parseInt(cell[1]), parseInt(cell[2]));
			}
		} else {
			// une case vide est selectionnee
			if (robotSelected != null) {
				// un robot a precedemment ete selectionne
				var cell = e.currentTarget.getAttribute("id").split("_");
				moveRobot(robotSelected, parseInt(cell[1]), parseInt(cell[2]));
			}
		}
	}, false);	
}

function selectRobotCell(idRobot) {
	console.log("Robot selected: " + idRobot);
	robotSelected = idRobot;
	selectRobot(idRobot);
}

function countDown() {
	if (countDownValue > 0 && !terminateGame) {
		document.getElementById("countDown").innerHTML = 
			"Il vous reste " + countDownValue + " secondes !";
		countDownValue--;
		setTimeout("countDown();", 1000);
	}
}

function refresh() {
	// replace les robots
	for (var i in robots) {
		var robot = robots[i];
		// deplacement du robot
		document.getElementById("cell_" + robot.line + "_" + robot.column)
				.appendChild(document.getElementById(robot.color));
		// desactivation des cellules coloriees
		while (document.querySelector("."+robot.color) != null) {
			document.querySelector("."+robot.color).setAttribute("class", ".cellule");
		}
	}
	// reaffiche la cible
	afficherCible();
	// ras des propositions
	propositions = new Array(); 
}

function getWinner(solutions) {
	var n = solutions.length-1;
	winner = solutions[n].player;
	var nbProp = solutions[n].proposition.length;
	for (var i = n-1; i >= 0; i--) {
		if (solutions[i].proposition.length <= nbProp) {
			winner = solutions[i].player;
		}
	}
}